
package com.xoa.plugin.ct;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xoa.dao.work.WorkMapper;
import com.xoa.global.proxy.TriggerSubject;
import com.xoa.model.nccloud.*;
import com.xoa.model.workflow.TriggerPlugIn;
import com.xoa.service.nccloud.*;
import com.xoa.util.DateFormat;
import com.xoa.util.DateUtil;
import com.xoa.util.ToJson;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *
 * 城投---人事个人转正表单
 *
 */
@Service
public class CTHRWorkApi {

    /*
    接口工具
     */
    @Autowired
    private INCCloudService nccloudService;

    //表数据
    private TriggerPlugIn tri = null;
    @Autowired
    INCCInterFaceLogService logService;

    @Autowired
    INCCPsndocService psndocService;

    @Autowired
    private WorkMapper workMapper;
    //人员对象
    private NccPsninfo nccPsninfo=null;
    @Autowired
    NccHrorgService nccHrorgService;
    @Autowired
    NccPsnclVService nccPsnclVService;
    @Autowired
    NccHrdeptService nccHrdeptService;
    @Autowired
    BdPsndocZzVService bdPsndocZzVService;

    public ToJson doRun(TriggerPlugIn tri)throws Exception {


        this.tri =tri;
        //当前表单id
        String run_id = tri.getRunId();
        //表id
        String tableName = tri.getFlowId();
        String reqeustBody=null;
        ToJson toJson=new ToJson();
        try {

            //====1、判断是否为新增人员调动办理表单
            if (StringUtils.isNotBlank(run_id) && tableName.equals("311")) {



                //=====2、请求nc接口保存获取主键
                // 封装NC接口表所需json数据
                reqeustBody = onversioncDto(tri.getModify(), run_id);
                // 请求发送保存
                String result = nccloudService.sendApi(nccloudService.regApplyUrl, reqeustBody);
                //转换json对象
                JSONObject rsjson = JSON.parseObject(result);
                //判断请求是否错误
                if (rsjson.getIntValue("code") == 1) {



                    //=====4、提交动作接口
                    // 接口调用成功 -- 取NC单据主键 pk_hi_stapply 存到记录行中
                    String pk = rsjson.getJSONObject("data").getString("pk_hi_regapply");
                    String billtype = rsjson.getJSONObject("data").getString("pk_billtype");

                    //保存单据主键和类型
                    this.saveBills(pk,billtype,run_id);

                    //请求发送保存json日志保存
                    this.saveLog(pk,reqeustBody,"城投人事个人转正311runid:"+run_id+"提交人员保存true",result,"1");

                    // 提交NC单据动作
                    //{"pk":"1001ZZ100000002R2LFJ","billType":"6115","checkNote":"","approveResult":"Y","action":"APPROVE"}
                    JSONObject[] jsonObjectRs = this.billsAction(pk,billtype,"","","SAVE");
                    //单据保存动作是否错误
                    if (jsonObjectRs[1].getIntValue("code") == 1) {


                        //请求发送动作json日志保存
                        this.saveLog(pk,jsonObjectRs[0].toJSONString(),"城投人事个人转正311runid:"+run_id+"提交人员保存动作true",jsonObjectRs[1].toJSONString(),"1");
                        toJson.setFlag(0);
                    } else {
                        //请求发送动作json日志保存
                        this.saveLog(pk,jsonObjectRs[0].toJSONString(),"城投人事个人转正311runid:"+run_id+"提交人员保存动作false",jsonObjectRs[1].toJSONString(),"0");

                        toJson.setMsg(jsonObjectRs[1].getString("message"));
                        toJson.setFlag(1);
                    }
                } else {
                    //请求发送保存json日志保存
                    this.saveLog("",reqeustBody,"城投人事个人转正311runid:"+run_id+"提交人员保存false",result,"0");

                    toJson.setMsg(rsjson.getString("message"));
                    toJson.setFlag(1);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            //请求发送保存json日志保存
            this.saveLog("","","城投人事个人转正311runid:"+run_id+"false",e.getMessage(),"0");

            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * 表单数据拼接json
     *
     * @param formdata
     * @param runId
     * @return
     * @throws Exception
     */

    public String onversioncDto(String formdata, String runId) throws Exception {
        nccPsninfo = new NccPsninfo();
        //将表单数据json数组解析List<Map<String, Object>>
        List<Map<String, Object>> data = JSONArray.parseObject(formdata, List.class);
        JSONObject jsonObject = new JSONObject();

        for (Map<String, Object> datum : data) {
            switch (datum.get("key").toString()) {
                case "DATA_230"://姓  名

                    break;
                case "DATA_231"://性  别
                    break;
                case "DATA_232"://出生年月
                    break;
                case "DATA_233"://政治面貌
                    break;
                case "DATA_234"://籍贯
                    break;
                case "DATA_235"://入党时间
                    break;
                case "DATA_236"://学历
                    break;
                case "DATA_237"://身份证号码
                    break;
                case "DATA_239"://所在部门
                    break;
                case "DATA_240"://现任岗位
                    break;
                case "DATA_241"://入职时间
                    break;
                case "DATA_221"://试用期限几个月
                    break;
                case "DATA_222"://试用多少  至
                    break;
                case "DATA_223"://试用多少
                    jsonObject.put("regulardate",datum.get("value").toString());//转正日期
                    break;
                case "DATA_224"://组织


                    break;
                case "DATA_247"://组织pk
                    String pk_orgName=datum.get("value").toString();
                    Map<String,Object> mapParam=new HashedMap<>();
                    mapParam.put("pkOrg",pk_orgName);
                    List<NccHrorg> nccHrorgListByMap = nccHrorgService.getNccHrorgListByMap(mapParam);
                    if(null==nccHrorgListByMap||nccHrorgListByMap.size()==0){
                        throw new RuntimeException(pk_orgName+"组织查询不到！");
                    }
                    jsonObject.put("pk_org",nccHrorgListByMap.get(0).getCode());//业务单元编码或名称

                    break;
                case "DATA_245"://工号
                    jsonObject.put("pk_psndoc",datum.get("value").toString());//人员姓名

                    break;
                case "DATA_62"://个人思想总结
                    break;
            }
        }


        jsonObject.put("pk_hi_regapply","");//f 主键，更新时必填
        jsonObject.put("apply_date", DateFormat.getFormatByUse("yyyy-MM-dd",new Date()));//申请日期

        jsonObject.put("pk_billtype","6111");//固定值6111
        jsonObject.put("pk_group","0");//集团编码或名称，默认写0

        String[] dateArry = jsonObject.getString("apply_date").split("-");
        jsonObject.put("bill_code", "CTRSZZ" + dateArry[0] + "" + dateArry[1] + "" + runId); //申请单编号


        jsonObject.put("creator","");// 创建人姓名，填提交人员姓名|------不要填写
        jsonObject.put("billmaker","NCCOA");//制单人姓名，填提交人员姓名|------不要填写
        jsonObject.put("approve_state","-1");//固定值-1
        jsonObject.put("probation_type","1");//试用类型：1=入职试用、       2=转岗试用|
        jsonObject.put("trialresult","1");//试用结果：1=转正、2=延长试用期、3=未通过试用|
        jsonObject.put("trialdelaydate","");//延长试用日期|
        jsonObject.put("pk_tutor","");//督导人| f
        jsonObject.put("memo","");//备注说明|  f
        jsonObject.put("ifsynwork","Y");//是否同步履历，默认写Y|
        jsonObject.put("ishrssbill","N");//固定值N|
        jsonObject.put("isneedfile","N");//固定值N|
        jsonObject.put("assgid","1");//固定值1|

        String danJuJson = "{\"billhead\":" + jsonObject.toJSONString() + "}";

        return danJuJson;
    }


    /**
     * 日志保存
     * @param pk
     * @param reqeustBody
     * @param name
     * @param result
     * @throws Exception
     */
    private void saveLog(String pk,String reqeustBody,String name,String result,String state)throws Exception{
        NCCInterfaceLog ncclog = new NCCInterfaceLog();
        ncclog.setBusinessNo(pk);
        ncclog.setContent(reqeustBody);
        ncclog.setName(name);
        ncclog.setResult(result);
        ncclog.setState(state);
        ncclog.setDisposeState("0");
        logService.save(ncclog);
    }


    /**
     * 单据动作
     * @param bills
     * @return
     * @throws Exception
     */
    public JSONObject[] billsAction(String... bills)throws Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pk",bills[0]);//单据主键
        jsonObject.put("billType",bills[1]);//单据类型编码
        jsonObject.put("checkNote",bills[2]);//批语
        jsonObject.put("approveResult",bills[3]);//审批结果
        jsonObject.put("action",bills[4]);//单据动作名称
        //请求发送动作
        String rs = nccloudService.sendApi(nccloudService.billactionUrl, jsonObject.toJSONString());

        return new JSONObject[]{jsonObject,JSON.parseObject(rs)};
    }

    /**
     * 保存单据信息
     * @param pk
     * @param billsType
     * @param run_id
     * @throws Exception
     */
    public void saveBills(String pk,String billsType,String run_id)throws Exception{
        // 保存主键的动作
        List<String> key = new ArrayList();
        key.add("pk_hi_stapply='"+pk+"'");
        key.add("billsType='"+billsType+"'");
        Map<String, Object> param = new HashMap();
        param.put("tableName", "flow_data_311");
        param.put("keys", key);
        param.put("runId", run_id);
        workMapper.update(param);
    }

}

